package org.ala.tiktools.sharddb.mybatis.transaction;

import java.util.function.Consumer;
import java.util.function.Function;

import org.ala.tiktools.mybatis.spring.TikToolsMyBatisSpringContext;
import org.ala.tiktools.sharddb.exception.ShardDBRuntimeException;
import org.ala.tiktools.sharddb.tx.IShardTransaction;
import org.ala.tiktools.sharddb.tx.ShardDataSourceTransactionManager;
import org.ala.tiktools.sharddb.tx.ShardTransactionThreadLocal;
import org.ala.tiktools.sharddb.tx.IShardTransaction.ICompensation;

/**
 *	本地分布式事务工具类
 *
 *	@author ala
 *	@date 2025年5月6日
 */
public class ShardTransactionUtils {

	
	/**
	 * 	在分布式事务内部做事情
	 */
	public static <T> T doTransaction(Function<IShardTransaction, T> consumer, ICompensation compensation) {
		ShardDataSourceTransactionManager txManager = TikToolsMyBatisSpringContext.getBean(ShardDataSourceTransactionManager.class);
		IShardTransaction tx = txManager.open(10000);
		ShardTransactionThreadLocal.setTx(tx);
		try {
			T t = consumer.apply(tx);
			tx.commit(compensation);
			return t;
		} catch (Exception e) {
			throw new ShardDBRuntimeException(e);
		} finally {
			ShardTransactionThreadLocal.clear();
		}
	}
	
	
	/**
	 * 	在分布式事务内部做事情
	 */
	public static void doTransaction(Consumer<IShardTransaction> consumer, ICompensation compensation) {
		ShardDataSourceTransactionManager txManager = TikToolsMyBatisSpringContext.getBean(ShardDataSourceTransactionManager.class);
		IShardTransaction tx = txManager.open(10000);
		ShardTransactionThreadLocal.setTx(tx);
		try {
			consumer.accept(tx);
			tx.commit(compensation);
		} catch (Exception e) {
			throw new ShardDBRuntimeException(e);
		} finally {
			ShardTransactionThreadLocal.clear();
		}
	}
	
}
